﻿namespace Groundwork.Extensions
{
    using System;
    using System.Collections.ObjectModel;
    
    /// <summary>
    /// TryGet Extensions
    /// </summary>
    public static class TryGet
    {
        /// <summary>
        /// Attempts to get a value from an Array of values.
        /// </summary>
        /// <typeparam name="T">Type of value to find</typeparam>
        /// <param name="value">current value</param>
        /// <param name="find">value to find</param>
        /// <param name="found">found value</param>
        /// <returns>returns true if the value was found in the array</returns>
        public static bool TryGetValue<T>(this Array value, T find, out T found) where T : IComparable<T>
        {
            found = default(T);
            for (int index = 0; index < value.Length; index++)
            {
                if (value.GetValue(index).Equals(find))
                {
                    found = (T)value.GetValue(index);
                    return true;
                }
            }
            
            return false;
        }

        /// <summary>
        /// Attempts to get a value from the ObservableCollection of values
        /// </summary>
        /// <typeparam name="T">Type of the value to find</typeparam>
        /// <param name="value">current value</param>
        /// <param name="find">value to find</param>
        /// <param name="found">found value</param>
        /// <returns>returns true if the value was found in the ObservableCollection</returns>
        public static bool TryGetValue<T>(this ObservableCollection<T> value, T find, out T found) where T : IComparable<T>
        {
            found = default(T);
            for (int index = 0; index < value.Count; index++)
            {
                if (value[index].Equals(find))
                {
                    found = (T)value[index];
                    return true;                   
                }
            }

            return false;
        }

        /// <summary>
        /// Attempts to find a value from the array of string values provided.
        /// </summary>
        /// <typeparam name="T">Type of the value to find</typeparam>
        /// <param name="value">current value</param>
        /// <param name="find">value to find</param>
        /// <param name="found">found value</param>
        /// <returns>returns true if the value was found in the string array</returns>
        public static bool TryGetValue<T>(this string[] value, string find, out string found) where T : IComparable<T>
        {
            found = null;
            for (int index = 0; index < value.Length; index++)
            {
                if (value[index].Equals(find))
                {
                    found = value[index];
                    return true;                    
                }
            }
            
            return false;
        }
    }
}
